<template>
  <div style="width: 100%; height: 100vh; background-color: dodgerblue; overflow: hidden">
    <!--overflow: hidden去掉边距-->
    <div style="width: 400px; margin: 150px auto">
      <!--auto表示居中-->
      <div style="color: #cccccc; font-size: 30px; text-align: center; padding: 30px">欢迎注册</div>
      <el-form ref="formRef" :model="form"  :rules="rules">
        <el-form-item prop="username">
          <el-input :prefix-icon="UserFilled" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            :prefix-icon="Lock"
            v-model="form.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirm">
          <el-input
            type="password"
            :prefix-icon="Lock"
            v-model="form.confirm"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%" type="primary" @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { UserFilled, Lock } from '@element-plus/icons-vue'

import request from '../utils/request'
import { ref, unref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

const form = ref<any>({})
const formRef = ref<any>(null)

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirm: [{ required: true, message: '请确认密码', trigger: 'blur' }]
}

const register = () => {
  const { username, password, confirm } = form.value
  if (password !== confirm) {
    ElMessage.error('两次密码不一致')

    return
  }
  formRef.value?.validate((valid: boolean) => {
    // 验证请求，只有在输入了账号密码才能发送请求
    // form要与el-form ref="form"命名的名字一样
    if (valid) {
      request.post('/user/register', unref(form)).then((res: any) => {
        console.log(res)
        if (res.code === '200') {
          ElMessage.success('注册成功')

          router.push('/login') // 注册成功后页面跳转到首页
        } else {
          ElMessage.error(res.msg)

        }
      })
    }
  })
}
</script>

<style scoped></style>
